﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class Theme_3_Download : PowerCreator.LMS.Web.Base.WebBasePage
{
    PowerCreator.LMS.Web.Download.DownType opDownloadType = new PowerCreator.LMS.Web.Download.DownType();
    PowerCreator.LMS.Web.Download.Download opDownload = new PowerCreator.LMS.Web.Download.Download();
    protected PowerCreator.LMS.Web.Config.WebConfig config = new PowerCreator.LMS.Web.Config.WebConfig();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Title = config.GetLanagerValueByKey("theme_OpenDownload_TitleInfo", PowerCreator.LMS.Language.LanagetItemType.Page);

            ViewState["DownloadID"] = "0";
            ViewState["DownloadTypeID"] = "0";
            if (Request.QueryString["DownloadID"] != null)
            {
                string downloadid = Request.QueryString["DownloadID"].ToString();
                ViewState["DownloadID"] = downloadid;
            }

            //BinderDownloadType();

            string search = GetSearch();
            BinderPager(search);
            BinderDownload(search,1);
        }
    }

    protected override void InitPage()
    {
        base.InitPage();
    }

    //private void BinderDownloadType()
    //{ 
    //    //绑定下载类型
    //    string search = "";
    //    DataTable dt = opDownloadType.Query(search);
    //    rpt_DownloadType.DataSource = dt;
    //    rpt_DownloadType.DataBind();
    //}

    private string GetSearch()
    {
        StringBuilder sbSearch = new StringBuilder();
        if (ViewState["DownloadID"].ToString() != "0")
        {
            sbSearch.Append(string.Format("DownID = {0} and ", ViewState["DownloadID"]));
        }
        if (ViewState["DownloadTypeID"].ToString() != "0")
        {
            sbSearch.Append(string.Format("FKDownDownTypeID = {0} and ", ViewState["DownloadTypeID"]));
        }
        sbSearch.Append(" DownState = 1 ");
        return sbSearch.ToString();
    }
    private void BinderPager(string search)
    {
        AspNetPager1.PageSize = PowerCreator.LMS.Web.Config.WebConfig.PageSize;
        AspNetPager1.RecordCount = opDownload.Count(search);
    }
    private void BinderDownload(string search,int pageIndex)
    {
        string orderBy = " DownUpdateTime desc ";
        //string orderBy = " DownClickNum desc ,DownUpdateTime desc ";
        DataTable dt = opDownload.Query(search, orderBy, PowerCreator.LMS.Web.Config.WebConfig.PageSize, pageIndex);
        dt.Columns.Add("ImageUrl");

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (!string.IsNullOrEmpty(dt.Rows[i]["DownUrl"].ToString()))
            {
                string fileExtension=string.Empty;
                string url = dt.Rows[i]["DownUrl"].ToString();
                string[] urls = url.Split('.');
                if (url.Length > 1)
                    fileExtension = urls[urls.Length - 1];

                dt.Rows[i]["ImageUrl"] = "images/File/" + fileExtension+".jpg";
            }
            else
            {
                dt.Rows[i]["ImageUrl"] = "../1/images/GauntEagleGem.gif";
            }
            //if (string.IsNullOrEmpty(dt.Rows[i]["DownImgUrl"].ToString()))
            //{
            //    dt.Rows[i]["DownImgUrl"] = "~/Theme/1/images/GauntEagleGem.gif";
            //}
        }
        rpt_Download.DataSource = dt;
        rpt_Download.DataBind();
        
    }
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        string search = GetSearch();
        BinderDownload(search, AspNetPager1.CurrentPageIndex);
    }
    protected void rpt_DownloadType_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName.ToString() == "lshow")
        {
            ViewState["DownloadID"] = "0";
            ViewState["DownloadTypeID"] = e.CommandArgument.ToString();
            string search = GetSearch();
            BinderPager(search);
            BinderDownload(search, 1);
        }
    }
    protected void rpt_Download_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName.ToString() == "ldown")
        {
            PowerCreator.LMS.Download.Entity.VOTDownload voDownload = new PowerCreator.LMS.Download.Entity.VOTDownload();
            voDownload = opDownload.Load(int.Parse(e.CommandArgument.ToString()));
            if (voDownload.DownID > 0)
            {
                string strFileName = voDownload.DownUrl;
                //Response.AddHeader("Connection", "Keep-Alive");
                //Response.ContentType = "application/octet-stream";
                string path = Server.MapPath("~/" + strFileName);
                if (System.IO.File.Exists(path))
                {

                    voDownload.DownClickNum += 1;
                    //voDownload.DownUpdateTime = DateTime.Now;
                    opDownload.Update(voDownload);


                    PowerCreator.LMS.Common.Script.Script.RedirectURL(PowerCreator.LMS.Common.Utils.WebUtils.WebRoot + "/" + strFileName);
                    //打开要下载的文件
                    //System.IO.FileStream r = new System.IO.FileStream(path, System.IO.FileMode.Open);
                    ////设置基本信息

                    //Response.Buffer = false;
                    //Response.AddHeader("Connection", "Keep-Alive");
                    //Response.ContentType = "application/octet-stream";
                    //Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(path));
                    //Response.AddHeader("Content-Length", r.Length.ToString());

                    //while (true)
                    //{
                    //    //开辟缓冲区空间
                    //    byte[] buffer = new byte[1024];
                    //    //读取文件的数据
                    //    int leng = r.Read(buffer, 0, 1024);
                    //    if (leng == 0)//到文件尾，结束
                    //        break;
                    //    if (leng == 1024)//读出的文件数据长度等于缓冲区长度，直接将缓冲区数据写入
                    //        Response.BinaryWrite(buffer);
                    //    else
                    //    {
                    //        //读出文件数据比缓冲区小，重新定义缓冲区大小，只用于读取文件的最后一个数据块
                    //        byte[] b = new byte[leng];
                    //        for (int i = 0; i < leng; i++)
                    //            b[i] = buffer[i];
                    //        Response.BinaryWrite(b);
                    //    }
                    //}
                    //r.Close();//关闭下载文件
                    //Response.End();//结束文件下载



                   

                    //Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(Server.MapPath("~/" + strFileName)));
                    //Response.TransmitFile(filename);
                    voDownload.DownClickNum += 1;
                    //voDownload.DownUpdateTime = DateTime.Now;
                    opDownload.Update(voDownload);

                    string search = GetSearch();
                    BinderDownload(search, AspNetPager1.CurrentPageIndex);
                }
                else
                {
                    Label lbl_msg = (Label)e.Item.FindControl("lbl_msg");
                    lbl_msg.Text = config.GetLanagerValueByKey("ResourceList_msg_m2", PowerCreator.LMS.Language.LanagetItemType.Page);
                }
            }
            
        }
    }
}
